package HtServer;

import HtServer.GrpcDataSet.DataSetImpl;

import io.grpc.servlet.ServletAdapter;
import io.grpc.servlet.ServletServerBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;


@WebServlet(urlPatterns = {"/HT_GRPC.DBGreeter/*"}, asyncSupported = true)
public class HtgrpcServlet extends HttpServlet {

    private final ServletAdapter servletAdapter =
            new ServletServerBuilder().addService(new DataSetImpl()).buildServletAdapter();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<p>HtgrpcServlet get method only for test!</p>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        if (ServletAdapter.isGrpc(request))
        if (isGrpc(request))
        {
            System.out.println("HT_GRPC.DBGreeter doPost");

//            servletAdapter.doPost(request, response);
        } else {
            System.out.println(" not dogrpc");
            response.setContentType("text/html");
            response.getWriter().println("<p>Hello non-gRPC2 client!</p>");
        }
    }


    private boolean isGrpc(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.startsWith("application/grpc");
    }
}
